package com.yunsc.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunsc.common.exception.YunscException;
import com.yunsc.product.dto.GoodsSkuDTO;
import com.yunsc.product.service.YunscGoodsService;
import com.yunsc.product.vo.GoodsInfoVO;
import com.yunsc.store.dao.YunscCartDao;
import com.yunsc.store.dto.CartParamsDTO;
import com.yunsc.store.entity.YunscCartEntity;
import com.yunsc.store.entity.YunscUserGradeEntity;
import com.yunsc.store.service.YunscCartService;
import com.yunsc.store.service.YunscUserGradeService;
import com.yunsc.store.service.YunscUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("yunscCartService")
public class YunscCartServiceImpl extends ServiceImpl<YunscCartDao, YunscCartEntity> implements YunscCartService {

    @Resource
    private YunscGoodsService goodsService;
    @Resource
    private YunscUserGradeService userGradeService;
    @Resource
    private YunscUserService userService;


    @Override
    public void addCart(Integer userId, CartParamsDTO param, Integer storeId) {
        YunscCartEntity cart = new YunscCartEntity();
        BeanUtils.copyProperties(param, cart);
        cart.setUserId(userId);
        cart.setStoreId(storeId);
        this.save(cart);
    }

    @Override
    public int queryUserCartCount(Integer userId) {
        if (userId == null){
            return 0;
        }
        LambdaQueryWrapper<YunscCartEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YunscCartEntity::getUserId, userId);
        lqw.eq(YunscCartEntity::getIsDelete, 0);
        List<YunscCartEntity> list = this.list(lqw);
        return list.stream().mapToInt(YunscCartEntity::getGoodsNum).sum();
    }

    @Override
    public Map<String, Object> queryUserCart(Integer userId) {
        // 返回结果
        Map<String, Object> map = new HashMap<>();

        LambdaQueryWrapper<YunscCartEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YunscCartEntity::getUserId, userId);
        lqw.eq(YunscCartEntity::getIsDelete, 0);
        lqw.orderByDesc(YunscCartEntity::getCreateTime);
        List<YunscCartEntity> carts = this.list(lqw);
        if (CollectionUtils.isEmpty(carts)) {
            map.put("cartTotal", 0);
            map.put("list", Collections.emptyList());
            return map;
        }
        carts.forEach(cart -> {
            Integer goodsId = cart.getGoodsId();
            String goodsSkuId = cart.getGoodsSkuId();
            GoodsInfoVO goods = goodsService.queryGoodsInfo(goodsId, goodsSkuId);
            // 设置商品价格
            GoodsSkuDTO skuInfo = goods.getSkuInfo();
            String goodsPrice = skuInfo.getGoodsPrice();
            // 获取用户会员等级
            YunscUserGradeEntity userGrade = userGradeService.queryUserGrade(userId);
            if (userGrade != null){
                // 会员折扣
                // 会员折扣比例
                String equity = userGrade.getEquity();
                Map equityMap = JSON.parseObject(equity, Map.class);
                String gradeRatio = (String) equityMap.get("discount");   // 9.7折
                // 会员折扣价格（原价*97%=现价）
                BigDecimal gradePriceGoods = new BigDecimal(goodsPrice).multiply(new BigDecimal(gradeRatio))
                        .multiply(new BigDecimal("0.1")).setScale(2, RoundingMode.HALF_UP);
                goods.getSkuInfo().setGoodsPrice(String.valueOf(gradePriceGoods));
            }
            cart.setGoods(goods);
        });
        int cartTotal = queryUserCartCount(userId);
        map.put("cartTotal", cartTotal);
        map.put("list", carts);
        return map;
    }

    @Override
    public Integer updateCartById(Integer userId, CartParamsDTO param) {
        Integer goodsId = param.getGoodsId();
        String goodsSkuId = param.getGoodsSkuId();
        Integer goodsNum = param.getGoodsNum();
        GoodsInfoVO goodsInfoVO = goodsService.queryGoodsInfo(goodsId, goodsSkuId);
        if (goodsNum > goodsInfoVO.getSkuInfo().getStockNum()) {
            throw new YunscException("很抱歉, 该商品库存数量不足，请重新选择");
        }
        UpdateWrapper<YunscCartEntity> updateWrapper = new UpdateWrapper<YunscCartEntity>()
                .eq("goods_id", goodsId)
                .eq("goods_sku_id", goodsSkuId)
                .eq("user_id", userId)
                .eq("is_delete", 0)
                .set("goods_num", goodsNum);

        boolean update = this.update(updateWrapper);
        if (!update) {
            throw new YunscException("更新购物车失败");
        }

        return queryUserCartCount(userId);

    }

    @Override
    public Integer clearUserCart(Integer userId, List<Integer> cartIds) {
        // UpdateWrapper<YunscCartEntity> updateWrapper = new UpdateWrapper<YunscCartEntity>()
        //         .eq("user_id", userId).eq("is_delete", 0)
        //         .in("id", cartIds)
        //         .set("is_delete", 1);
        // this.update(updateWrapper);
        this.removeByIds(cartIds);
        return queryUserCartCount(userId);
    }
}